今天要介紹透過使用reorderables來拖曳元件,改變列表的順序
輸入下方指令安裝套件
flutter pub add reorderables
flutter pub get
建立drag_screen.dart的StatefulWidget
宣告nameList
List<String> nameList = [
'Liam',
'Olivia',
'Noah',
'Emma',
'Oliver',
'Charlotte',
'Elijah',
'Amelia',
'James',
'Ava',
'William',
'Sophia',
'Benjamin',
'Isabella',
'Lucas',
'Mia',
'Henry',
'Evelyn',
'Theodore',
];
_scrollController
來控制滾動的內容_onReorder
來將list的索引值改變在Widget build(BuildContext context)
內加入下方程式碼
ScrollController _scrollController = PrimaryScrollController.of(context) ?? ScrollController();
void _onReorder(int oldIndex, int newIndex) {
setState(() {
final row = nameList.removeAt(oldIndex);
nameList.insert(newIndex, row);
});
}
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(
Icons.arrow_back_ios,
),
onPressed: () {
Navigator.of(context).pop();
},
),
title: const Text(
"拖曳列表",
),
),
body: CustomScrollView(
controller: _scrollController,
slivers: [
ReorderableSliverList(
delegate: ReorderableSliverChildListDelegate(
nameList
.map(
(name) => SizedBox(
height: 50,
child: Card(
color: const Color(0xFFB0D7FD),
child: ListTile(
title: Text(name),
),
),
),
)
.toList(),
),
onReorder: _onReorder,
),
],
),
);
}